/*
 * @Author: your name
 * @Date: 2021-08-05 10:59:23
 * @LastEditTime: 2021-08-05 11:15:19
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \vuestudy\vue\15-组件\components\swiper.js
 */
Vue.component("swiper-header", {
  props: ["list"],
  template: `
    <div id="con">
        <div class="arrow left" @click="left">《</div>
        <div class="arrow right" @click="right">》</div>
        <img v-for="(item,i) in list" v-show="i===active" :src="item" alt="图片">
        <ul class="dian">
            <li v-for="(item,i) in list" @click="goto(i)" :class="{active:i===active}"></li>
        </ul>
    </div>
    `,
  data() {
    return {
      // 定义定时器
      time: -1,
      // 当前选中的索引
      active: 0,
    };
  },
  mounted() {
    // clearInterval(this.timer)
    // 调用定时器滚动方法
    this.run();
  },
  methods: {
    // 定时器滚动方法
    run() {
      this.time = setInterval(() => {
        // this.active++;
        if (++this.active === this.list.length) {
          this.active = 0;
        }
      }, 3000);
    },
    left() {
      // 先清除定时器
      clearInterval(this.time);
      if (--this.active < 0) this.active = this.list.length - 1;
      // 等执行完再调用 定时器 以免定时器的累加
      this.run();
    },
    right() {
      // 先清除定时器
      clearInterval(this.time);
      if (++this.active === this.list.length) this.active = 0;
      // 等执行完再调用 定时器 以免定时器的累加
      this.run();
    },
    goto(i) {
      // 先清除定时器
      clearInterval(this.time);
      this.active = i;
      // 等执行完再调用 定时器 以免定时器的累加
      this.run();
    },
  },
});
